import re
import time
import requests
import uuid
import datetime
from flask import make_response, request, send_from_directory
from flask_restful import abort
from flask_login import current_user, login_user
from funcy import project
from sqlalchemy.orm.exc import NoResultFound
from sqlalchemy.exc import IntegrityError
from funcy import partial
import json
import logging
from flask_mail import Message
from redash.utils.encryption import hly_uname, hly_password
from redash import models, limiter, mail, settings
from redash.permissions import (
    require_default,
    require_admin,
)
from redash.handlers.base import (
    BaseResource,
    require_fields,
    get_object_or_404,
    paginate,
    order_results as _order_results,
)

from redash.authentication.account import (
    invite_link_for_user,
    send_invite_email,
    send_password_reset_email,
    send_verify_email,
)
from redash.settings import parse_boolean
from redash import settings
from redash.serializers import (
    serialize_data_result_to_xlsx,
)
import sys
import random
from typing import List


class ProjectNewResource(BaseResource):
    def get(self):
        result = models.Project.get_id()
        return result[0]

    @require_default
    def post(self):
        req = request.get_json(force=True)
        require_fields(req, ("code","name"))
        if not hly_password():
            msg = "请使用正版软件！设备信息：" + hly_uname() + "；许可证：" + settings.REGISTER["common"]
            abort(400, message=msg)
        project_id=req["id"]
        signatory = req["signatory"] if len(str(req["signatory"]))>0 else 0
        socialsecurity = req["socialsecurity"] if len(str(req["socialsecurity"]))>0 else 0
        neednum = req["neednum"] if len(str(req["neednum"]))>0 else 1
        amount = req["amount"] if len(str(req["amount"]))>0 else 0
        periods = req["periods"] if len(str(req["periods"]))>0 else 0
        code = req["code"]
        bytstatus = req["bytstatus"]
        schooled =  req["schooled"] if "schooled" in req else ""
        
        project = models.Project(
        id=project_id,
        org=self.current_org,
        bill_date = req["bill_date"],
        customerid = req["customerid"]  if "customerid" in req else "0",
        code = code,
        name = req["name"] if "name" in req else "",
        neednum = neednum,
        amount = amount,
        major =req["major"] if "major" in req else "",
        schooled =schooled,
        certificate =req["certificate"]  if "certificate" in req else "",
        location =req["location"] if "location" in req else "",
        socialsecurity =socialsecurity,
        area = req["area"] if "area" in req else "",
        bytstatus = bytstatus,
        periodunit = req["periodunit"] if "periodunit" in req else "",
        periods = periods,
        signingtime = req["signingtime"] if "signingtime" in req else None,
        expirationtime = req["expirationtime"] if "expirationtime" in req else None,
        status = req["status"],
        purpose = req["purpose"] if "purpose" in req else "",
        certificatestatus = req["certificatestatus"] if "certificatestatus" in req else "",
        locationneed = req["locationneed"] if "locationneed" in req else "",
        message = req["message"] if "message" in req else "",
        signatory = signatory,
        userid = req["userid"],
        orgunitid = req["orgunitid"] if "orgunitid" in req else "0",
        contractcode= req["contractcode"] if "contractcode" in req else "",
        threeperson= req["threeperson"] if "threeperson" in req else "",
        )
        strsql ="""update public.projectdetail set amount=round("""+str(amount)+""",2)
            where projectid = """+str(project_id)
        try:
            models.db.session.add(project)
            models.db.session.execute(strsql)
            models.db.session.commit()
        except IntegrityError as e:
            if "code" in str(e):
                abort(400, message="编号已存在.")
            abort(500)


class ProjectResource(BaseResource):
    def get(self, project_id):
        result = models.Project.get_by_id(project_id)
        result2= models.Workflow.workflowedit("project",0,project_id,self.current_user.id,self.current_org.id)
        return result.to_dict()

    @require_default
    def post(self, project_id):
        req = request.get_json(force=True)
        require_fields(req, ("code","name"))
        if not hly_password():
            msg = "请使用正版软件！设备信息：" + hly_uname() + "；许可证：" + settings.REGISTER["common"]
            abort(400, message=msg)
        signatory = req["signatory"] if len(str(req["signatory"]))>0 else 0
        socialsecurity = req["socialsecurity"] if len(str(req["socialsecurity"]))>0 else 0
        neednum = req["neednum"] if len(str(req["neednum"]))>0 else 1
        amount = req["amount"] if len(str(req["amount"]))>0 else 0
        periods = req["periods"] if len(str(req["periods"]))>0 else 0
        code = req["code"]
        bytstatus = req["bytstatus"]
        schooled =  req["schooled"] if "schooled" in req else ""

        project = models.Project.get_by_id(project_id)

        params = dict(bill_date=req["bill_date"],customerid = req["customerid"] if "customerid" in req else "0",
            code = code,name = req["name"] if "name" in req else "",neednum = neednum, amount = amount, major =req["major"] if "major" in req else "",
            schooled =schooled, certificate =req["certificate"] if "certificate" in req else "",
            location =req["location"] if "location" in req else "",socialsecurity =socialsecurity,
            area = req["area"] if "area" in req else "",bytstatus = bytstatus,periodunit = req["periodunit"] if "periodunit" in req else "",
            periods = periods,signingtime = req["signingtime"] if "signingtime" in req else None,
            expirationtime = req["expirationtime"] if "expirationtime" in req else None,status = req["status"],
            purpose = req["purpose"] if "purpose" in req else "", certificatestatus = req["certificatestatus"] if "certificatestatus" in req else "",
            locationneed = req["locationneed"] if "locationneed" in req else "", message = req["message"] if "message" in req else "", 
            signatory = signatory, orgunitid = req["orgunitid"] if "orgunitid" in req else "0",
            contractcode= req["contractcode"] if "contractcode" in req else "",threeperson= req["threeperson"] if "threeperson" in req else "")
        strsql ="""update public.projectdetail set amount=round("""+str(amount)+""",2)
            where projectid = """+str(project_id)
        try:
            self.update_model(project, params)
            models.db.session.execute(strsql)
            models.db.session.commit()
        except IntegrityError as e:
            if "code" in str(e):
                abort(400, message="编号已存在.")
            abort(500)

class ProjectBytstatusResource(BaseResource):
    @require_default
    def post(self, project_id):
        req = request.get_json(force=True)
        bytstatus = req["bytstatus"]
        project = models.Project.get_by_id(project_id)
        params = dict(bytstatus = bytstatus)
        try:
            self.update_model(project, params)
            models.db.session.commit()
        except IntegrityError as e:
            if "code" in str(e):
                abort(400, message="状态更改失败.")
            abort(500)
class ProjectdeleteResource(BaseResource):
    @require_default
    def post(self, project_id):
        strsql="select count(*)From public.paymentactivity where projectid="+str(project_id)
        isdelheck =models.enums.Enums.get_selsql(strsql)
        if isdelheck[0] >0:
            abort(400, message="项目已有收付款，不能删除.")

        project =  models.Project.get_by_id(project_id)
        strsql="""delete From  attaches where sourcetype='project' and org_id="""+str(self.current_org.id)+""" and sourceid="""+ project_id +"""; 
            delete From projectdetail where projectid="""+ project_id +"""; 
            delete From employeeactivity where sourcetype='project' and employeeid="""+ project_id +""" ; """
        models.db.session.execute(strsql)
        models.db.session.delete(project)
        models.db.session.commit()

class ProjectListResource(BaseResource):
    def post(self):
        req = request.get_json(force=True)
        page = req["page"]
        page_size = req["pagesize"]
        customername = req["customername"]if "customername" in req else ""
        representative = req["representative"]if "representative" in req else ""
        orgunitname = req["orgunitname"]if "orgunitname" in req else ""
        difference = str(req["difference"]) if "difference" in req else ""
        code = req["code"] if "code" in req else ""
        name = req["name"] if "name" in req else ""
        major = req["major"] if "major" in req else ""
        area = req["area"] if "area" in req else ""
        userid = str(req["userid"]) if "userid" in req else ""
        bytstatus= req["bytstatus"] if "bytstatus" in req else ""
        certificate = req["certificate"] if "certificate" in req else ""
        location = req["location"] if "location" in req else ""
        status = str(req["status"]) if "status" in req else ""
        begindate= req["begindate"] if "begindate" in req else ""
        enddate= req["enddate"] if "enddate" in req else ""
        genjinbegindate= req["genjinbegindate"] if "genjinbegindate" in req else ""
        genjinenddate= req["genjinenddate"] if "genjinenddate" in req else ""
        mainpage= req["mainpage"] if "mainpage" in req else ""
        datadown = req["datadown"] if "datadown" in req else False
        orderfield = req["orderfield"] if "orderfield" in req else "bill_dateformat"
        order = req["order"] if "order" in req else 0
        if orderfield=="code" :
            orderfield ="t1.code"
        elif orderfield=="name":
            orderfield ="t1.name"
        elif orderfield=="major":
            orderfield ="t1.major"
        elif orderfield=="area":
            orderfield ="t1.area"
        elif orderfield=="bill_dateformat":
            orderfield ="t1.bill_date"
        elif orderfield=="genjindate":
            orderfield ="t10.genjindate"
        else:
            orderfield ="t1.code"        

        strwhere ="t1.org_id=" +str(self.current_org.id)
        if code !="" :
            strwhere = strwhere + " and t1.code like '%"+code+"%'"
        if name !='' :
            strwhere = strwhere + " and t1.name like '%"+name+"%'"
        if major !='' :
            strwhere = strwhere + " and  '"+major+"' = ANY(t1.major)"
        if area !='' :
            strwhere = strwhere + " and t1.area like '%"+area+"%'"
        if bytstatus !='' :
            strwhere = strwhere + " and t1.bytstatus like '%"+bytstatus+"%'"
        if certificate !='' :
            strwhere = strwhere + " and '"+certificate+"' = ANY(t1.certificate)"
        if location !='' :
            strwhere = strwhere + " and t1.location like '%"+location+"%'"
        if customername !='' :
            strwhere = strwhere + " and t3.strcustomername like '%"+customername+"%'"
        if orgunitname !='' :
            strwhere = strwhere + " and t5.name like '%"+orgunitname+"%'"
        if status !='' :
            strwhere = strwhere + " and t1.status = '"+status+"'"
        if representative !='':
            strwhere = strwhere + " and t3.representative like '%"+representative+"%'"
        if difference =="1":
            strwhere = strwhere + " and t1.neednum-COALESCE(t7.employeecount,0)>0 and t1.bytstatus !='完结' "
        elif difference =="2":
            strwhere = strwhere + " and (t1.neednum-COALESCE(t7.employeecount,0)<=0 or t1.bytstatus ='完结') "
        if begindate !='' :
            strwhere = strwhere + " and t1.bill_date >= '"+begindate+"'"
        if enddate !='' :
            strwhere = strwhere + " and to_char(t1.bill_date,'YYYY-MM-DD') <= '"+enddate+"'"
        if genjinbegindate !='' :
            strwhere = strwhere + " and t10.genjindate >= '"+genjinbegindate+"'"
        if genjinenddate !='' :
            strwhere = strwhere + " and to_char(t10.genjindate,'YYYY-MM-DD') <= '"+genjinenddate+"'"
        if userid !="":
            strwhere = strwhere + " and t1.userid = '"+userid+"'"
            
        if "super_admin" not in self.current_user.permissions  and userid !="":
            strwhere = strwhere + """ and  (t1.userid='""" + userid + """' or  t1.userid in (
                WITH RECURSIVE cte(keys,items,parentkeys) AS 
                (
                    select *From (with RECURSIVE le (keys,items,parentkeys) as
                    (select   (items)->>'key' as keys,json_array_elements((items)->'children') as items,'0' as parentkeys
                    from   (select unnest(details) items From orgstruct where orgstruct_enum='admin' and expire_date is null) AA
                    union all
                    select (items)->>'key' as keys,json_array_elements((items)->'children') as items,keys as parentkeys from le)
                    select le.* from le inner join users on to_number(le.keys, '9999999999999999999')= users.orgunit_id where users.id='""" + userid + """') T1
                    UNION ALL  
                    SELECT  (items)->>'key' as keys,json_array_elements((items)->'children') as items,keys as parentkeys FROM cte
                )
                SELECT users.id FROM cte inner join users on to_number((cte.items)->>'key', '9999999999999999999')=users.orgunit_id
                ))"""
        strgetfield =""" t1.id as projectid,t1.id,to_char(t1.bill_date,'YYYY-MM-DD') bill_dateformat,t1.code,t1.name,t1.customerid,t1.neednum,t1.amount,"""
        strgetfield =strgetfield +""" array_to_string(t1.major,',') major,t1.schooled,array_to_string(t1.certificate,',') certificate,t1.location,
                case when t1.socialsecurity=1 then '有' else '无' end socialsecuritystr,
                t1.area,t1.periodunit,t1.periods,t1.bytstatus,t1.signingtime,t1.expirationtime,t1.status,
                t1.purpose,t1.certificatestatus,t1.locationneed,t1.message,t1.signatory,t1.userid,t1.updated_at,t1.created_at,
                t1.orgunitid,t1.threeperson,case when t1.status=0 then '草稿' when t1.status=1 then '审核中' else '已审核' end as strstatus,
                COALESCE(t2.name,'') as username,COALESCE(t3.strcustomername,'') as strcustomername,COALESCE(t4.name,'')  as signatoryname,
                COALESCE(t3.representative,'') as representative,
                COALESCE(t5.name,'') as orgunitname,COALESCE(t7.employeecount,0) employeecount,
                t1.neednum-COALESCE(t7.employeecount,0) as difference,
                COALESCE(t9.amount,0) as amountin,COALESCE(to_char(t9.paydate,'YYYY-MM-DD'),'') paydateformatin,
                COALESCE(to_char(t10.genjindate,'YYYY-MM-DD'),'') genjindate """

        tblname = """ public.project t1 left join public.users t2 on t1.userid=t2.id
                left join public.customers t3 on t1.customerid=t3.id
                left join public.users t4 on t1.signatory=t4.id
				left join public.orgunit t5 on t1.orgunitid=t5.id
                left join (select count(*) as employeecount,projectid From public.projectdetail group by projectid) t7 on t1.id=t7.projectid
                left join (select sum(t2.amount) as amount,t2.projectid,
                max(t1.paydate) paydate
                From public.payment t1 inner join public.paymentactivity t2 on t1.id=t2.paymentid
                where t1.type=1 group by t2.projectid) t9 on t1.id=t9.projectid
                left join(select employeeid,max(updated_at) as genjindate From public.employeeactivity 
				where sourcetype='project'group by employeeid) t10 on t1.id=t10.employeeid """
        #orderfield ="t1.id"
        if not datadown :
            result = models.Enums.get_pagequery(tblname,strgetfield,orderfield,page_size,page,order,strwhere)
            return result[0]
        else :
            queryshowfield = models.QueryShowField.get_by_code('projectlist1')
            ps = queryshowfield.to_dict()
            fieldsshow = ps['fieldsshow']
            fieldsall = json.loads(json.dumps(ps['fieldsall'])) 
            columns =[]
            strsql="select " + strgetfield + " from " + tblname +" where " +strwhere
            strgetfield = ""
            for i in range(len(fieldsall)):
                if fieldsall[i]["key"] in fieldsshow:
                    columns.append({ 'name' : fieldsall[i]["title"]})
                    strgetfield = strgetfield +","+  fieldsall[i]["key"] +" as "+ fieldsall[i]["title"]
                    
            orderfield = req["orderfield"] if "orderfield" in req else "code"
            strsql = "select " + strgetfield[1:] + " from (" + strsql + ") t1 order by "+orderfield
            if order==0 :
                strsql= strsql+" ASC "
            else :
                strsql= strsql+" DESC "
            strsql = """select array_to_json(array_agg(row_to_json(t))) from (""" + strsql + """) t """
            data = models.Enums.get_selsql(strsql)

            article_info = {}
            da1 = json.loads(json.dumps(article_info))
            da1['columns'] = columns #[{"name": "code", "friendly_name": "code", "type": null}, {"name": "name", "friendly_name": "name", "type": null}]
            da1['rows'] = data[0] #[{"code": "code", "name": "name"}, {"code": "code1", "name": "name1"}]

            query_result = da1

            result = serialize_data_result_to_xlsx(query_result,"xiangmu")
            return send_from_directory(result, "xiangmu.xlsx",as_attachment=True)

#     选单
class ProjectSelListResource(BaseResource):
    def post(self):
        req = request.get_json(force=True)
        bytstatus = req["bytstatus"]
        billid = str(req["id"])  if "id" in req else "0"

        strsql ="""select t1.*
            From public.project t1 left join 
            (select t2.projectid, sum(t2.amount) as amount
            from public.payment t1 inner join public.paymentactivity t2 on t1.id=t2.paymentid
            where t1.type=1
            group by t2.projectid) t2 on t1.id=t2.projectid
            where t1.status=2 and t1.org_id=""" +str(self.current_org.id) +" and (( "
        # if bytstatus !='' :
        #     strsql = strsql+ """ and t1.bytstatus='"""+bytstatus+"""' """
        strsql = strsql+ """ t1.amount- COALESCE(t2.amount,0)>0
        ) or t1.id in(select projectid from public.paymentactivity where id="""+billid+"""))"""

        strsql = """select array_to_json(array_agg(row_to_json(t))) from (""" + strsql + """) t """
        result = models.Enums.get_selsql(strsql)
        return result[0]